package org.yonggan.web;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.TimeUnit;

@EnableWebMvc
@Configuration
@RestController
public class WebConfig implements WebMvcConfigurer {


    /**
     * 矩阵变量“q”
     *
     * @param petId
     * @param q
     */
    // /pets/42;q=11;r=22
    @GetMapping("/pets/{petId}")
    public void findPet(@PathVariable String petId, @MatrixVariable int q) {
        System.out.println(petId); // 42
        System.out.println(q);// 11
    }

    // // GET /owners/42;q=11/pets/21;q=22   ----
    @GetMapping("/owners/{ownerId}/pets/{petId}")
    public void findPet01(@MatrixVariable(name = "q", pathVar = "ownerId") int q1,
                          @MatrixVariable(name = "q", pathVar = "petId") int q2) {
        System.out.println(q1); // 11
        System.out.println(q2);// 22
    }

    /**
     * 添加 http 缓存
     *
     * @param registry
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public-resources/")
                .setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
    }
    @GetMapping("/book/{id}")
    public ResponseEntity<Book> showBook(@PathVariable Integer id) {
        Book book = new Book();
        book.setId(id);
        book.setBookName("克苏米神话");
        book.setVersion("0001");
        return ResponseEntity.ok().cacheControl(
                CacheControl.maxAge(30, TimeUnit.MINUTES)).eTag(book.getVersion()).body(book);
    }

    @GetMapping("/test")
    public ResponseEntity<String> getRequestHeaderParams (@RequestHeader(value = "Accept-Language" ,required = false) String key ) {

        System.out.println(key);
        return new ResponseEntity<String>(HttpStatus.NOT_MODIFIED);
    }
}